<template>
  <scroll-view
    class="content"
    show-scrollbar
    enable-back-to-top
    scroll-into-view="bottom"
  >
    <view class="record-box">
      <view
        v-for="item in recordObj.list"
        :class="['record-item', { isMine: item.senderId == USER_INFO.id }]"
        :key="item.id"
      >
        <image class="avat" :src="item.sender.headPic" mode="scaleToFill" />
        <text>{{ item.content }}</text>
      </view>
      <view id="bottom"></view>
    </view>
  </scroll-view>
  <view class="input-box">
    <uni-easyinput
      class="input"
      v-model="inputVal"
      placeholder="请输入内容"
      @confirm="send"
    ></uni-easyinput>
  </view>
</template>

<script setup lang="ts">
import socket from "@/utils/socket";

import { onShow } from "@dcloudio/uni-app";
import {
  computed,
  getCurrentInstance,
  onBeforeMount,
  onMounted,
  reactive,
  ref,
} from "vue";
import { createRoom, findChatroom } from "@/api/room";
import { getHis } from "@/api/chat-history";
let inputVal = ref("");
const USER_INFO = ref({
  id: "",
});
const recordObj = reactive({
  list: [],
  roomId: 0,
});

const receiveUser = ref({
  id: "",
  username: "",
});
onMounted(() => {
  const instance = getCurrentInstance().proxy;
  const eventChannel = instance.getOpenerEventChannel();

  uni.getStorage({
    key: "USER_INFO",
    success(res) {
      Object.assign(USER_INFO.value, res.data);
    },
  });

  eventChannel.on("dataFromIndex", (user) => {
    console.log("dataFromIndex", user);
    receiveUser.value = user;
    recordObj.roomId = user.roomId;

    getHistory(recordObj.roomId);

    socket.on("connect", () => {
      const payload = {
        chatroomId: recordObj.roomId,
        userId: receiveUser.value.id,
      };
      socket.emit("joinRoom", payload);
    });
    socket.on("message", (data) => {
      console.log("on message--->", data);
      if (data.type === "joinRoom") {
        console.log("用户 " + data.userId + "加入聊天室");
      } else {
        getHistory(recordObj.roomId);
        console.log("recordObj.list--->", recordObj.list);
      }
    });
  });
});

// onBeforeMount(() => socket.close());

const getHistory = async (id: number) => {
  let data = await getHis(id);
  recordObj.list = data;
  setTimeout(() => {
    document.getElementById("bottom")?.scrollIntoView({ block: "end" });
  }, 300);
};

const send = async (data: string) => {
  const payload2 = {
    sendUserId: USER_INFO.value.id,
    chatroomId: recordObj.roomId,
    message: {
      type: "text",
      content: data,
    },
  };
  socket.emit("sendMessage", payload2);
  // 发消息后再次获取记录
  setTimeout(() => {
    inputVal.value = "";
  }, 100);
};
</script>

<style lang="scss" scoped>
#bottom {
  height: 200rpx;
}
.input-box {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 150rpx;
  background: #a9a8a8c8;
}

.record-item {
  position: relative;
  margin: 20rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  &.isMine {
    flex-direction: row-reverse;
    text {
      text-align: right;
    }
  }
  text {
    flex: 1;
  }
  .avat {
    width: 100rpx;
    height: 100rpx;
  }
}
</style>
